package thread;

import java.util.concurrent.Semaphore;

/**
 * Created with IntelliJ IDEA.
 * Description: semaphore解决线程安全问题
 * User: 王圆豪
 * Date: 2025-05-07
 * Time: 23:40
 */
public class Demo38 {
    private static int count = 0;
    public static void main(String[] args) throws InterruptedException {
        Semaphore semaphore = new Semaphore(1);
        Thread t1 = new Thread(()->{
            try {
                semaphore.acquire();
                for (int i = 0; i < 50000; i++) {
                    count++;
                }
                semaphore.release();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        Thread t2 = new Thread(()->{
            try {
                semaphore.acquire();
                for (int i = 0; i < 50000; i++) {
                    count++;
                }
                semaphore.release();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        t1.start();
        t2.start();
        Thread.sleep(100);
        System.out.println(count);
    }
}
